package com.atguigu.gmall.product;

import java.util.concurrent.*;

/**
 * 异步编排
 */
public class CompletableFutureDemo2 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService threadPool = new ThreadPoolExecutor(2,
                5,
                2L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        //串行 1  如果有其他新线程就是并行任务之一
        CompletableFuture<String> oneCompletableFuture=  CompletableFuture.supplyAsync(() -> {
            try {
                //验证串行
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("上一个任务");
            return "上一个任务返回值";
        }, threadPool).thenApplyAsync((t) -> {
            System.out.println("thenApplyAsync:t: = " + t);
            return "当前任务返回值";
        }, threadPool).whenCompleteAsync((t, u) -> {
            System.out.println("whenCompleteAsync:t: = " + t);
        });
        //串行 2
//        CompletableFuture.supplyAsync(() -> {
//            System.out.println("上一个任务");
//            return "上一个任务返回值";
//        }, threadPool).thenAcceptAsync((t) -> {
//            System.out.println("thenAcceptAsync:t: = " + t);
//        }, threadPool).whenCompleteAsync((t, u) -> {
//            System.out.println("whenCompleteAsync:t: = " + t);
//        });
        //串行 3
//        CompletableFuture.supplyAsync(() -> {
//            System.out.println("上一个任务");
//            return "上一个任务返回值";
//        }, threadPool).thenRunAsync(() -> {
//            System.out.println("我是当前任务");
//        }, threadPool).whenCompleteAsync((t, u) -> {
//            System.out.println("whenCompleteAsync:t: = " + t);
//        });
        //并行2
        CompletableFuture<String> twoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("我是并行的第二个任务");
            return "456";
        },threadPool);
        //并行3
        CompletableFuture<String> threeCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("我是并行的第三个任务");
            return "789";
        }, threadPool);

        //多任务组合
        CompletableFuture.allOf(oneCompletableFuture,twoCompletableFuture,threeCompletableFuture).join();
        System.out.println("集齐三颗龙珠召唤神龙");
    }
}
